/*
 *  YBModalAlert.m
 *  YeePay
 *
 *  Created by enalex on 11/17/10.
 *  Copyright 2010 YeePay. All rights reserved.
 *
 */

#define ALERT_HIDING_TIME 3

#import "YBModalAlert.h"
static YBModalAlert *sharedInstance = nil;

@implementation YBModalAlert
@synthesize alertView;
@synthesize killTimer;
@synthesize isTimer;

+ (void)deletesharedInstance {
	if (sharedInstance) {
		[sharedInstance release];
		sharedInstance = nil;
	}
}

+ (YBModalAlert *)sharedInstance {
	if (nil == sharedInstance) {
		sharedInstance = [[YBModalAlert alloc] init];
		UIAlertView *newAlertView = [[UIAlertView alloc] init];
		newAlertView.delegate = sharedInstance;
		sharedInstance.alertView = newAlertView;
		[newAlertView release];
    
	}
	else if (nil == sharedInstance.alertView) {
		UIAlertView *newAlertView = [[UIAlertView alloc] init];
		newAlertView.delegate = sharedInstance;
		sharedInstance.alertView = newAlertView;
		[newAlertView release];
	}

	return sharedInstance;
}

- (void)hidingAlert:(NSTimer *)timer {
	[timer invalidate];
	[self.alertView dismissWithClickedButtonIndex:0 animated:YES];
	CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)alertView:(UIAlertView*) aView clickedButtonAtIndex:(NSInteger) anIndex {
	CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)showAlertToUser:(NSString *)title message:(NSString *)message button:(NSString *)button isTimer:(BOOL)timer {
//	CFRunLoopRef currentLoop = CFRunLoopGetCurrent();
	NSString *buttonName = nil;
	if (!button) {
		buttonName = @"取消";
	}
	else {
		buttonName = button;
	}
	// Create Alert
	// alertTitle = nil;
	self.alertView.title = title;
	self.alertView.message = message;
	[self.alertView addButtonWithTitle:buttonName];
	self.alertView.cancelButtonIndex = 0;
	
	[alertView show];
	if (YES == timer) {
		self.killTimer = [NSTimer scheduledTimerWithTimeInterval:ALERT_HIDING_TIME target:self selector:@selector(hidingAlert:) userInfo:nil repeats:NO];
		CFRunLoopRun();
		self.alertView = nil;
		[self.killTimer invalidate];
	}
	else {
		//[self.alertView dismissWithClickedButtonIndex:0 animated:YES];
		self.alertView = nil;
	}
}

- (void)dealloc {
	[killTimer release];
	[alertView release];
	[super dealloc];
}
@end

